package com.jy.rhin.infra.repo.document.validation.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.api.misc.MiscAPI;
import com.jy.common.StringUtil;
import com.jy.framework.base.utils.Serializer;
import com.jy.rhin.domain.document.template.CDADocumentTemplateService;
import com.jy.rhin.facade.infra.controller.dto.CDADocumentTemplateNodeDto;
import com.jy.rhin.infra.repo.document.submission.mapper.DocumentValidateResultDetailMapper;
import com.jy.rhin.infra.repo.document.submission.mapper.DocumentValidateResultMapper;
import com.jy.rhin.infra.repo.document.submission.po.DocumentValidateResultDetailPO;
import com.jy.rhin.infra.repo.document.submission.po.DocumentValidateResultPO;
import com.jy.rhin.infra.repo.document.template.po.CDADocumentTemplatePo;
import com.jy.rhin.infra.repo.document.template.query.CDADocumentTemplateQueryHandler;
import com.jy.rhin.infra.repo.document.validation.mapper.DocumentValidationFileMapper;
import com.jy.rhin.sdk.dto.document.query.DocumentValidateResultDetailDto;
import com.jy.rhin.sdk.dto.document.query.DocumentValidateResultDto;
import com.jy.rhin.sdk.dto.tongji.WenDangZLFXDto;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.parser.Parser;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author dhl
 * @date 2022/6/10
 * @Description 文档汇总统计查询handler
 */
@Slf4j
@Service
public class DocumentValidateQueryHandler {

	@Resource
	private DocumentValidateResultMapper documentValidateResultMapper;
	@Resource
	private DocumentValidateResultDetailMapper documentValidateResultDetailMapper;
	@Resource
	private DocumentValidationFileMapper documentValidationFileMapper;

	@Resource
	private CDADocumentTemplateQueryHandler cdaDocumentTemplateQueryHandler;
	@Resource
	private CDADocumentTemplateService cdaDocumentTemplateService;
	@Resource
	private MiscAPI miscApi;

	public Page<DocumentValidateResultDto> resultPage(String documentId, String documentType, String kaiShiSJ,
			String jieShuSJ, String validateResult, long pageNo, long pageSize) {
		Page<DocumentValidateResultPO> page = new Page<DocumentValidateResultPO>(pageNo, pageSize);
		QueryWrapper<DocumentValidateResultPO> queryWrapper = new QueryWrapper<DocumentValidateResultPO>();
		queryWrapper.eq(!StringUtil.isNullOrEmpty(documentId),"document_id", documentId);
		queryWrapper.between("document_create_time", kaiShiSJ,jieShuSJ+" 23:59:59");
		queryWrapper.eq(!StringUtil.isNullOrEmpty(validateResult),"validate_result", validateResult);
		queryWrapper.eq(!StringUtil.isNullOrEmpty(documentType),"document_type", documentType);
		queryWrapper.orderByDesc("documentCreateTime");
		Page<DocumentValidateResultDto> result = new Page<DocumentValidateResultDto>(pageNo, pageSize);
		page = documentValidateResultMapper.selectPage(page, queryWrapper);
		if(!ObjectUtils.isEmpty(page)){
			List<DocumentValidateResultDto> list = Serializer.deserializeArray(Serializer.serialize(page.getRecords()), DocumentValidateResultDto.class);
			BeanUtils.copyProperties(page, result);
			result.setRecords(list);
		}
		return result;

	}

	public DocumentValidateResultDto resultDetail(Long id) {
		DocumentValidateResultDto info = new DocumentValidateResultDto();
		BeanUtils.copyProperties(documentValidateResultMapper.selectById(id), info);
		QueryWrapper<DocumentValidateResultDetailPO> queryWrapper = new QueryWrapper<DocumentValidateResultDetailPO>();
		queryWrapper.eq("result_id", id);
		queryWrapper.orderByAsc("detail_result");
		List<DocumentValidateResultDetailPO> details = documentValidateResultDetailMapper.selectList(queryWrapper);
		CDADocumentTemplatePo templatePo = cdaDocumentTemplateQueryHandler.getByTemplateName(info.getDocumentType());
		if(!ObjectUtils.isEmpty(details)){
			List<DocumentValidateResultDetailDto> list = Serializer.deserializeArray(Serializer.serialize(details), DocumentValidateResultDetailDto.class);
			//关联展示文档编辑器内容
			getErrorCol(templatePo,list);
			info.setDetails(list);
		}
		return info;
	}

	private void getErrorCol(CDADocumentTemplatePo templatePo ,List<DocumentValidateResultDetailDto> list){
		String cdcDoc = cdaDocumentTemplateService.previewCDADocumentTemplateByNodes(Serializer.deserialize(templatePo.getTemplateNodes(), CDADocumentTemplateNodeDto.class));
		JXDocument jxDocument = JXDocument.create(Parser.xmlParser().parseInput(cdcDoc, ""));
		JXNode root = jxDocument.selNOne("//ClinicalDocument");
		list.forEach(l->{
			l.setResultId(null);
			if("0".equals(l.getDetailResult())){
				try{
					JXNode node = getNode(l.getContent().split(" ")[0],root);
					if(l.getContent().contains("值域校验错误")){
						l.setErrorCol(getNode("@code",node).asString()+"|"+getNode("@displayName",node).asString());
					}else{
						l.setErrorCol(node.asString());
					}
					if(l.getContent().contains("数据元:")){
						l.setResultId(miscApi.getDetailByShuJuYuan(l.getContent().split("数据元:")[1]).getData().getId());
					}
				}catch(Exception e){
					log.error(e.getMessage());
				}
			}
		});
	}

	JXNode getNode(String path, JXNode root) {
		JXNode jxNode = null;
		if (path.endsWith("/text")) { // /text特殊处理 上级目录转换成element找到tag=text取值 转换为jxnode
			String prePath = path.substring(0, path.length() - 5);
			JXNode preNode = root.selOne(prePath);
			if (Objects.nonNull(preNode)) {
				jxNode = new JXNode(preNode.asElement().parent().getElementsByTag("text").text());
			}
		} else {
			jxNode = root.selOne(path);
		}
		return jxNode;
	}


	public List<DocumentValidateResultPO> getDocumentValidateResult() {
		QueryWrapper<DocumentValidateResultPO> wrapper = new QueryWrapper<>();
		return documentValidateResultMapper.selectList(wrapper);

	}

	public List<WenDangZLFXDto>  getwenDangZBFXList(String kaiShiRQ, String jieShuRQ) {
		return documentValidateResultMapper.getwenDangZBFXList(kaiShiRQ,jieShuRQ);

	}

	public Integer getRuleNumByFileType(String fileType) {
		return documentValidationFileMapper.getRuleNum(fileType);
	}
}
